package com.leoman.messageapi.service.impl;

import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.SendMessageErrorException;
import com.leoman.messageapi.service.PrivateLetterApiService;
import com.leoman.privateletter.dao.PrivateLetterDao;
import com.leoman.privateletter.entity.PrivateLetter;
import com.leoman.privateletter.entity.vo.PrivateLetterVo;
import com.leoman.reourceapi.service.impl.ResourceApiServiceImpl;
import com.leoman.user.dao.UserAttentionDao;
import com.leoman.user.dao.UserInfoDao;
import com.leoman.user.entity.UserAttention;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.entity.vo.FansVo;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 私信serviceImpl
 * Created by 涂奕恒 on 2016/6/12.
 */
@Service
public class PrivateLetterApiServiceImpl implements PrivateLetterApiService {

    @Autowired
    private PrivateLetterDao privateLetterDao;

    @Autowired
    private UserAttentionDao userAttentionDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public Page<PrivateLetter> letterPage(Long userId, Long sourceId, Integer pageNum, Integer pageSize) {
        int[] info = ResourceApiServiceImpl.changePageParams(pageNum, pageSize);
        Page<PrivateLetter> page = privateLetterDao.findListSession(userId, sourceId, new PageRequest(info[0] - 1, info[1]));
        FansVo fansVo;

        for (PrivateLetter privateLetter : page.getContent()) {
            fansVo = new FansVo();
            fansVo.setUserId(privateLetter.getUser().getId());
            fansVo.setNickname(privateLetter.getUser().getNickname());
            fansVo.setAvater(ImageUtil.clearUploadUrl(privateLetter.getUser().getAvater()));
            privateLetter.setFromUserInfo(fansVo);

            fansVo = new FansVo();
            fansVo.setUserId(privateLetter.getToUser().getId());
            fansVo.setNickname(privateLetter.getToUser().getNickname());
            fansVo.setAvater(ImageUtil.clearUploadUrl(privateLetter.getToUser().getAvater()));
            privateLetter.setToUserInfo(fansVo);

            privateLetter.setImage(ImageUtil.clearUploadUrl(privateLetter.getImage()));
            privateLetter.setVoice(ImageUtil.clearUploadUrl(privateLetter.getVoice()));
        }

        return page;
    }

    @Override
    @Transactional
    public List<PrivateLetterVo> letterList(Long userId) {
        List<PrivateLetterVo> list = new ArrayList<>();
        List<PrivateLetter> list1 = privateLetterDao.findListGroupByUserId(userId);
        List<PrivateLetter> list2 = privateLetterDao.findListGroupByToUserId(userId);

        List<PrivateLetter> tempList = privateLetterDao.findListByUserIdWithNoRead(userId);

        for (PrivateLetter privateLetter : tempList) {
            if (privateLetter.getIsRead().equals(Constant.MESSAGE_READ_STATUS_NO)) {
                privateLetter.setIsRead(Constant.MESSAGE_READ_STATUS_YES);
                privateLetterDao.save(privateLetter);
            }
        }

        for (PrivateLetter privateLetter : list1) {
            list.add(getPrivateLetterVo(privateLetter, true));
        }

        for (PrivateLetter privateLetter : list2) {
            list.add(getPrivateLetterVo(privateLetter, false));
        }

        return list;
    }

    private PrivateLetterVo getPrivateLetterVo(PrivateLetter privateLetter, Boolean isMe) {
        // isMe为true时，代表是别人给我发的私信列表；反之是我给别人发的私信列表
        UserInfo userInfo;
        if (isMe) {
            userInfo = privateLetter.getUser();
        } else {
            userInfo = privateLetter.getToUser();
        }

        PrivateLetterVo privateLetterVo = new PrivateLetterVo();
        privateLetterVo.setUserId(userInfo.getId());
        privateLetterVo.setAvater(ImageUtil.clearUploadUrl(userInfo.getAvater()));
        privateLetterVo.setNickname(userInfo.getNickname());
        privateLetterVo.setTime(privateLetter.getCreateDate());

        List<PrivateLetter> list = privateLetterDao.findList(privateLetter.getToUser().getId(), privateLetter.getUser().getId());
        if (null != list && list.size() > 0) {
            privateLetterVo.setContent(list.get(0).getContent());
        }

        return privateLetterVo;
    }

    @Override
    public void sendLetter(Long userId, Long toUserId, String content, Integer type, Integer length, MultipartRequest multipartRequest) throws SendMessageErrorException {
        // 检测双方之间是否互相关注过，如果没有，则不让发送私信
        Boolean flag = false;

        UserAttention userAttention1 = userAttentionDao.findOneInfo(userId, toUserId);
        UserAttention userAttention2 = userAttentionDao.findOneInfo(toUserId, userId);

        MultipartFile voice = multipartRequest.getFile("voice");
        MultipartFile image = multipartRequest.getFile("image");

        if (null != userAttention1 && null != userAttention2 && userAttention1.getStatus() == 0 && userAttention2.getStatus() == 0) {
            flag = true;
        }

        try {
            PrivateLetter privateLetter = new PrivateLetter();
            privateLetter.setUser(userInfoDao.findOne(userId));
            privateLetter.setToUser(userInfoDao.findOne(toUserId));
            privateLetter.setContent(content);
            privateLetter.setType(type);
            privateLetter.setLength(length);
            privateLetter.setIsRead(Constant.MESSAGE_READ_STATUS_NO);
            if (flag) {
                if (null != voice && voice.getSize() > 0) {
                    privateLetter.setVoice(FileUtil.save(voice, false).getPath());
                }
                if (null != image && image.getSize() > 0) {
                    FileBo fileBo = FileUtil.save(image, true);
                    privateLetter.setImage(fileBo.getPath());
                    privateLetter.setWidth(fileBo.getWidth());
                    privateLetter.setHeight(fileBo.getHeight());
                }
            } else {
                if ((null != voice && voice.getSize() > 0) || (null != image && image.getSize() > 0)) {
                    throw new SendMessageErrorException();
                }
            }

            privateLetterDao.save(privateLetter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void deleteLetter(Long userId, Long sourceId) {
        List<PrivateLetter> list = privateLetterDao.findListSession(userId, sourceId, new PageRequest(0, 10000)).getContent();

        for (PrivateLetter privateLetter : list) {
            privateLetterDao.delete(privateLetter);
        }
    }
}
